//
//  ZJProjectImgVC.m
//  这家测试项目
//
//  Created by IOS_DEVELOPER on 2017/6/28.
//  Copyright © 2017年 陈志凌. All rights reserved.
//

#import "ZJProjectImgVC.h"
#import "ZJProjectImgCell.h"
#import "ZJProjectImgModel.h"
#import "ZJProjectImgHeaderView.h"

#import <AVFoundation/AVAsset.h>
#import <AVFoundation/AVAssetImageGenerator.h>
#import <AVFoundation/AVTime.h>
#import <AVFoundation/AVFoundation.h>
#import <MediaPlayer/MediaPlayer.h>
#import <AVKit/AVKit.h>
@interface ZJProjectImgVC ()<UICollectionViewDelegate,UICollectionViewDataSource,MWPhotoBrowserDelegate>
@property (weak, nonatomic) IBOutlet UICollectionView *collectionView;
/**<数据源>*/
@property (nonatomic,strong) NSArray *dataArr;
/**<图片数组>*/
@property (nonatomic,strong) NSMutableArray *photoArr;
@property (nonatomic,strong) NSMutableArray *allPhotoArr;
@property (nonatomic, strong) AVPlayer *player;
@property (nonatomic, strong) AVPlayerViewController  *playerView;
@end

@implementation ZJProjectImgVC

- (void)viewDidLoad {
    [super viewDidLoad];
    if ([self.roomType isEqualToString:@"视频"]) {
        self.title = @"楼盘视频";
    }
    [self setupCollectionLayout];
}

-(void)setupCollectionLayout{
    UICollectionViewFlowLayout * layout = [[UICollectionViewFlowLayout alloc]init];
    if ([self.roomType isEqualToString:@"视频"]) {
        layout.itemSize = CGSizeMake(SCREEN_WIDTH - 20, 174);
    }else{
        layout.itemSize = CGSizeMake((self.view.width - 40) / 3, (self.view.width - 40) / 3);
        layout.headerReferenceSize =CGSizeMake(SCREEN_WIDTH - 20,40);
    }
    //设置每个item的大小
    
    layout.scrollDirection = UICollectionViewScrollDirectionVertical;
    layout.minimumInteritemSpacing = 0;
    layout.minimumLineSpacing = 0;
    
    self.photoArr = [NSMutableArray new];
    self.allPhotoArr = [NSMutableArray new];
    self.collectionView.collectionViewLayout = layout;
    
    [self sendRequest];
}
#pragma mark - ******************请求数据
-(void)sendRequest{
    [HUD showLoading:@"加载数据中..."];
    NSDictionary *parameter = [LRNetwork requestParameter:@{}];
    NSString *url;
    if ([self.roomType isEqualToString:@"视频"]) {
    url = [LRNetwork requestURL:@"cgi/video.php"];
    }else{
    url = [LRNetwork requestURL:@"cgi/picture.php"];
    }

    [LRNetwork netRequestPOSTWithRequestURL:url withParameter:parameter withReturnValeuBlock:^(id returnValue) {
        if ([self.roomType isEqualToString:@"视频"]) {
            self.photoArr = returnValue[@"video"];
         
        }else{
            self.dataArr = [ZJProjectImgModel mj_objectArrayWithKeyValuesArray:returnValue[@"picture"]];
            NSMutableArray * arr  = [ZJProjectImgModel mj_objectArrayWithKeyValuesArray:returnValue[@"picture"]];
            for (ZJProjectImgModel * model in self.dataArr) {
                for (NSDictionary * dict in model.pics) {
                    if (dict[@"pic_url"]) {
                        [self.allPhotoArr addObject:dict[@"pic_url"]];
                    }
                }
            }
            for (int i = 0; i < self.dataArr.count;i ++) {
                ZJProjectImgModel * model = self.dataArr[i];
                if (model.pics.count < 1) {
                    [arr removeObjectAtIndex:i];
                    self.dataArr = arr;
                    i = 0;
                }
            }

        }

        [self.collectionView reloadData];

        [HUD hide];
    } withErrorCodeBlock:^(NSInteger errorCode, NSString *errorMessage) {
        [HUD showErrorMsg:errorMessage];
    } withFailureBlock:^{
        
    }];
}

#pragma mark -UICollectionViewDataSource
-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
     if (![self.roomType isEqualToString:@"视频"]) {
    return self.dataArr.count;
     }else{
         return 1;
     }
}
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
     if (![self.roomType isEqualToString:@"视频"]) {
    ZJProjectImgModel * model = self.dataArr[section];
    NSArray * arr = model.pics;
    return arr.count;
     }else{
         return self.photoArr.count;
     }
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    ZJProjectImgCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"ZJProjectImgCell" forIndexPath:indexPath];
    
    if (![self.roomType isEqualToString:@"视频"]) {
        
        ZJProjectImgModel * model = self.dataArr[indexPath.section];
        NSArray * arr = model.pics;
        NSDictionary * dict = arr[indexPath.row];
        cell.playImg.hidden = YES;
        cell.bgView.hidden = YES;
        cell.titleLabel.hidden = YES;
        [cell.img sd_setImageWithURL:dict[@"pic_url"] placeholderImage:[UIImage imageNamed:kDefaultImageName]];

    }else{
        NSDictionary * dict = self.photoArr[indexPath.row];
        cell.contentView.layer.shadowColor = RGB(235, 235, 235).CGColor;;
        cell.contentView.layer.shadowOpacity = 0.3f;
        cell.contentView.layer.shadowOffset = CGSizeMake(0,0.1);
        cell.titleLabel.text = dict[@"title"];
        cell.bgView.hidden = NO;
        cell.bgView.alpha = 0.3f;
        cell.titleLabel.hidden = NO;
        [cell.img sd_setImageWithURL:dict[@"pic_url"] placeholderImage:[UIImage imageNamed:kDefaultImageName]];
    }
    return cell;
}


-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    [collectionView deselectItemAtIndexPath:indexPath animated:YES];
    if (![self.roomType isEqualToString:@"视频"]) {
    [self.photoArr removeAllObjects];
    ZJProjectImgModel * model = self.dataArr[indexPath.section];
    NSArray * arr = model.pics;
    for (NSDictionary * dict in arr) {
        [self.photoArr addObject:dict[@"pic_url"]];
    }
    
    MWPhotoBrowser *browser = [[MWPhotoBrowser alloc] initWithDelegate:self];
    // Set options
    
    browser.displayActionButton = NO;
    [browser showNextPhotoAnimated:YES];
    [browser showPreviousPhotoAnimated:YES];
    NSInteger index = [self.allPhotoArr indexOfObject:self.photoArr[indexPath.row]];
    [browser setCurrentPhotoIndex:index];
    UINavigationController *nc = [[UINavigationController alloc] initWithRootViewController:browser];
    
    nc.modalTransitionStyle = UIModalTransitionStyleCoverVertical;
    [self presentViewController:nc animated:YES completion:nil];
        
    }else{
         NSDictionary * dict = self.photoArr[indexPath.row];
        ZJActivityVC *vc = [[UIStoryboard storyboardWithName:@"Home" bundle:nil] instantiateViewControllerWithIdentifier:@"ZJActivityVC"];
        vc.urlStr = dict[@"link"];
        [self.navigationController pushViewController:vc animated:YES];
    }
}

-(UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
{
    if (![self.roomType isEqualToString:@"视频"]) {
        return UIEdgeInsetsMake(0,10,0,10);
    }else return UIEdgeInsetsMake(10,10,10,10);

}

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section{
        return 10;
        
}
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section{
        return 0;
}
- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath{
    
    UICollectionReusableView *reusableview = nil;

    if (kind == UICollectionElementKindSectionHeader){
        ZJProjectImgModel * model = self.dataArr[indexPath.section];
        
        NSString *CellIdentifier = [NSString stringWithFormat:@"Cell%ld", (long)[indexPath section]];
        [self.collectionView registerClass:[ZJProjectImgHeaderView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:CellIdentifier];
        
        ZJProjectImgHeaderView *headerView = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:CellIdentifier forIndexPath:indexPath];
        
        headerView.backgroundColor = RGB(245, 245, 245);
            reusableview = headerView;
            headerView.text = model.type;

    }
    
    return reusableview;
}

#pragma mark - MWPhotoBrowserDelegate

- (NSUInteger)numberOfPhotosInPhotoBrowser:(MWPhotoBrowser *)photoBrowser
{
    return self.allPhotoArr.count;
}

- (id <MWPhoto>)photoBrowser:(MWPhotoBrowser *)photoBrowser photoAtIndex:(NSUInteger)index
{
//    NSInteger photoIndex = [self.allPhotoArr indexOfObject:self.photoArr[index]];
    return [MWPhoto photoWithURL:[NSURL URLWithString:self.allPhotoArr[index]]];
}

- (void)photoBrowserDidFinishModalPresentation:(MWPhotoBrowser *)photoBrowser{
    
    [self dismissViewControllerAnimated:YES completion:nil];
    
}
- (NSString *)photoBrowser:(MWPhotoBrowser *)photoBrowser

      titleForPhotoAtIndex:(NSUInteger)index {
    NSString * str;
    for (ZJProjectImgModel * model in self.dataArr) {
        for (NSDictionary * dict in model.pics) {
            if ([dict[@"pic_url"] isEqualToString:self.allPhotoArr[index]]) {
                str = model.type;
                break;
            }
        }
    }
    
    return [NSString stringWithFormat:@"%lu/%lu(%@)",(unsigned long)index + 1,
            
            (unsigned long)self.allPhotoArr.count,str];
    
}
@end
